package codingforgreat.lchot150;

import java.util.*;

public class Lc054 {
    public List<Integer> spiralOrder(int[][] matrix) {
        int SR = 0;
        int SC = 0;
        int DR = matrix.length - 1;
        int DC = matrix[0].length - 1;
        List<Integer> res = new ArrayList<Integer>();
        while(SR <= DR && SC <= DC){
            process(matrix,SR++,SC++,DR--,DC--,res);
        }
        return res;

    }
    public void process(int[][] matrix,int SR,int SC,int DR,int DC,List<Integer> res){
        if(SR == DR){
            for(int i = SC;i <= DC;i++){
                res.add(matrix[SR][i]);
            }
        }else if(SC == DC){
            for(int i = SR;i <= DR;i++){
                res.add(matrix[i][SC]);
            }
        }else{
            int curR = SR;
            int curC = SC;
            while(curC < DC){
                res.add(matrix[SR][curC++]);
            }
            while(curR < DR){
                res.add(matrix[curR++][DC]);
            }
            while(curC > SC){
                res.add(matrix[DR][curC--]);
            }
            while(curR > SR){
                res.add(matrix[curR--][SC]);
            }
        }
    }
}
